<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="考试时间" prop="examDate">
        <el-date-picker clearable
          v-model="queryParams.examDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择考试时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="考试总分" prop="totalScore">
        <el-input
          v-model="queryParams.totalScore"
          placeholder="请输入考试总分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获得分数" prop="obtainedScore">
        <el-input
          v-model="queryParams.obtainedScore"
          placeholder="请输入获得分数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['topic:detail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column label="用户ID" align="center" prop="nickName" />
      <el-table-column label="关联培训任务ID" align="center" prop="taskName" />
      <el-table-column label="考试时间" align="center" prop="examDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.examDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试总分" align="center" prop="totalScore" />
      <el-table-column label="获得分数" align="center" prop="obtainedScore" />
      <el-table-column label="通过状态" align="center" prop="passStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.passStatus === 1" size="small">通过</el-tag>
          <el-tag v-else size="small" type="danger">未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="考试用时" align="center" prop="timeSpent">
        <template slot-scope="scope">
          <span>{{ scope.row.timeSpent }}秒</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['topic:detail:edit']"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看考试记录详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称:">
              <span>{{ form.nickName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训任务:">
              <span>{{ form.taskName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="考试时间:">
              <span>{{ parseTime(form.examDate, '{y}-{m}-{d}') }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试用时:">
              <span>{{ form.timeSpent }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="考试总分:">
              <span>{{ form.totalScore }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="获得分数:">
              <span>{{ form.obtainedScore }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="通过状态:">
              <el-tag v-if="form.passStatus === 1" type="success">通过</el-tag>
              <el-tag v-else type="danger">未通过</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通过率:">
              <span>{{ form.totalScore ? ((form.obtainedScore / form.totalScore * 100).toFixed(2) + '%') : '0%' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="答题详情:" v-if="form.answerDetails && form.answerDetails.length > 0">
          <el-card shadow="never" style="max-height: 400px; overflow-y: auto;">
            <el-table 
              :data="parseAnswerDetails(form.answerDetails)" 
              border 
              size="small"
              style="width: 100%">
              <el-table-column prop="topicId" label="题目ID" align="center" width="100"></el-table-column>
              <el-table-column prop="userAnswer" label="用户答案" align="center" width="100"></el-table-column>
              <el-table-column prop="standardAnswer" label="标准答案" align="center" width="100"></el-table-column>
              <el-table-column label="答题状态" align="center" width="100">
                <template slot-scope="scope">
                  <el-tag 
                    v-if="scope.row.userAnswer === scope.row.standardAnswer" 
                    type="success" 
                    size="small">
                    正确
                  </el-tag>
                  <el-tag 
                    v-else 
                    type="danger" 
                    size="small">
                    错误
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="得分" align="center" width="100">
                <template slot-scope="scope">
                  {{ scope.row.score }} / {{ scope.row.maxScore }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-form-item>
        
        <el-form-item label="答题详情:" v-else>
          <span>暂无详情</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDetail, getDetail, delDetail, addDetail, updateDetail } from "@/api/demo/topic/detail";

export default {
  name: "Detail",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试记录表格数据
      detailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        taskId: null,
        examDate: null,
        totalScore: null,
        obtainedScore: null,
        passStatus: null,
        timeSpent: null,
        answerDetails: null,
      },
      // 表单参数
      form: {},
      // 表单校验 - 移除所有必填验证
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询考试记录列表 */
    getList() {
      this.loading = true;
      listDetail(this.queryParams).then(response => {
        this.detailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        taskId: null,
        examDate: null,
        totalScore: null,
        obtainedScore: null,
        passStatus: null,
        timeSpent: null,
        answerDetails: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看详情";
      });
    },
    /** 解析答题详情 */
    parseAnswerDetails(answerDetails) {
      try {
        // 如果answerDetails是字符串，则解析为JSON
        if (typeof answerDetails === 'string') {
          return JSON.parse(answerDetails);
        }
        // 如果已经是数组，则直接返回
        if (Array.isArray(answerDetails)) {
          return answerDetails;
        }
        // 其他情况返回空数组
        return [];
      } catch (error) {
        console.error('解析答题详情失败:', error);
        return [];
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('topic/detail/export', {
        ...this.queryParams
      }, `detail_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>